package com.example.traning.mall.dal.redis.account;

import com.example.traning.mall.framework.common.util.json.JsonUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Repository;

import java.util.concurrent.TimeUnit;

/**
 * @author lei yu
 * @since 2024/10/15
 */
@Slf4j
@Repository
@RequiredArgsConstructor
public class AccountUserRedisDAO {

    private final StringRedisTemplate redisTemplate;

    private final long durationInMinute = 86400;

    /**
     * 缓存数据的KEY的前缀：用户状态数据
     */
    private final static String KEY_PREFIX_USER_STATE = "passport:user-state:";

    public void saveUserState(Long userId, UserCachePO userCachePO) {
        log.debug("开始处理【向缓存中写入用户信息】的数据访问，用户ID：{}，用户登录信息：{}", userId, userCachePO);
        String key = KEY_PREFIX_USER_STATE + userId;
        String json = JsonUtils.toJsonString(userCachePO);
        // k, v,
        redisTemplate.opsForValue().set(key, json, durationInMinute, TimeUnit.SECONDS);
    }

    public Boolean deleteUserState(Long userId) {
        log.debug("开始处理【从缓存中删除用户信息】的数据访问，用户ID：{}，", userId);
        String key = KEY_PREFIX_USER_STATE + userId;
        return redisTemplate.delete(key);
    }

    public void renewal(Long userId) {
        log.debug("开始处理【续期缓存中的用户信息】的数据访问，用户ID：{}，", userId);
        String key = KEY_PREFIX_USER_STATE + userId;
        redisTemplate.expire(key, durationInMinute, TimeUnit.SECONDS);
    }

    public UserCachePO getUserState(Long userId) {
        log.info("开始处理【从缓存中读取用户信息】的数据访问，用户ID：{}，", userId);
        String key = KEY_PREFIX_USER_STATE + userId;
        String json = redisTemplate.opsForValue().get(key);
        return JsonUtils.parseObject(json, UserCachePO.class);
    }

}
